$(function () {
    // 定义格式化时间方法
    function formatTime(time) {
        const date = new Date(time)
        const YYYY = date.getFullYear()
        const MM = padZero(date.getMonth() + 1)
        const DD = padZero(date.getDate())

        const HH = padZero(date.getHours())
        const mm = padZero(date.getMinutes())
        const ss = padZero(date.getSeconds())
        return `${YYYY}-${MM}-${DD} ${HH}:${mm}:${ss}`
    }
    // 补0
    const padZero = n => n > 9 ? n : '0' + n
    // todos 获取新闻列表
    $.ajax({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/news',
        success({ data, msg, status }) {
            // console.log(res);
            if (status !== 200) return alert(msg)
            const htmlStr = data.map(({ title, source, tags, time, cmtcount,img }) => {
                const htmlTag = tags.split(',')
                const htmlTags = htmlTag.map(item => `
                <span>${item}</span>
                `).join("")
                return `
                <div class="news-item">
                  <img class="thumb" src="http://www.liulongbin.top:3006${img}" alt="" />
                  <div class="right-box">
                    <h1 class="title">${title}</h1>
                    <div class="tags">
                       ${htmlTags}
                    </div>
                    <div class="footer">
                      <div>
                        <span>${source}</span>&nbsp;&nbsp;
                        <span>${formatTime(time)}</span>
                      </div>
                      <span>评论数：${cmtcount}</span>
                    </div>
                  </div>
                </div>
                `
            }).join('')

            $('#news-list').html(htmlStr)
        }
    })

})
    